package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"hotel/model/mysql"
	"hotel/model/redisInit"
	"hotel/pkg"

	"hotel/hotelrpc/hotelrpc"
	"hotel/hotelrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAddLogic) UserAdd(in *hotelrpc.UserAddRequest) (*hotelrpc.UserAddResponse, error) {
	// todo: add your logic here and delete this line
	senGet := redisInit.Rdb.Get("sendSmsAdd" + in.Phone)
	if senGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	var finHotel mysql.Hotel
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&finHotel)
	if finHotel.ID != 0 {
		return nil, fmt.Errorf("该账号已注册,请前去登录")
	}
	hotel := mysql.Hotel{
		Model:    gorm.Model{ID: finHotel.ID},
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&hotel)
	return &hotelrpc.UserAddResponse{
		Id: int64(hotel.ID),
	}, nil
}
